package cn.edu.sdjzu.xg.eagle.controller;

import cn.edu.sdjzu.xg.eagle.dao.SchoolDaoImpl;
import cn.edu.sdjzu.xg.eagle.entity.School;
import cn.edu.sdjzu.xg.eagle.exception.BaseException;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;

@WebServlet("/t1")
public class SchoolReadCtl extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        JSONObject message = new JSONObject();
        String id_str = request.getParameter("id");
        try{
            Long id_long = Long.parseLong(id_str);
            School school = SchoolDaoImpl.getInstance().find(id_long);
            String school_json = JSON.toJSONString(school, JSONWriter.Feature.ReferenceDetection);
            response.getWriter().println(school_json);
        }catch (BaseException e){
            message.put("message", e.getMessage());
            response.getWriter().println(message);
            e.printStackTrace();
        }catch (SQLException e){
            message.put("message","数据库操作异常");
            response.getWriter().println(message);
            e.printStackTrace();
        }catch (Exception e){
            message.put("message","网络异常");
            response.getWriter().println(message);
            e.printStackTrace();
        }
    }

    protected void doPut(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        JSONObject message = new JSONObject();
        try{
            Collection<School>schoolList = SchoolDaoImpl.getInstance().findAll();
            String school_json = JSON.toJSONString(schoolList,JSONWriter.Feature.ReferenceDetection);
            response.getWriter().println(school_json);
        }catch (BaseException e){
            message.put("message", e.getMessage());
            response.getWriter().println(message);
            e.printStackTrace();
        }catch (SQLException e){
            message.put("message","数据库操作异常");
            response.getWriter().println(message);
            e.printStackTrace();
        }catch (Exception e){
            message.put("message","网络异常");
            response.getWriter().println(message);
            e.printStackTrace();
        }
    }
}
